package com.example.waimaiandroid.login;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.transition.FragmentTransitionSupport;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.waimai.HttpUtil.MyGet;
import com.example.waimai.HttpUtil.MyPost;
import com.example.waimai.MainActivity;
import com.example.waimai.context.UserInfoContext;
import com.example.waimai.pojo.User;
import com.example.waimai.util.MyCountDownUtil;
import com.example.waimai.util.MyThreadPool;
import com.example.waimai.util.RequestPermissionUtil;
import com.example.waimai.util.ShowPopuWIndow;
import com.example.waimaiandroid.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.widget.Toast.LENGTH_SHORT;

/*
* 登录注册的逻辑应该是： app 进入 先到登录注册页面，从本地缓存中取值判断是否已经登录过
* 如果登录过，就直接带着用户信息 跳转到 主页面
* 如果没有登录过，就停留在登录界面
* 本地缓存 利用 sharedPreference  使用 SharePreferences 对象来获取数据
* 使用 Editor 对象 来设置数据
*  用户信息缓存？
* */
public class LoginActivity extends AppCompatActivity {

    private ImageView userImage;
    private TextView userImageStr;


     Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    String tokenId = (String) msg.obj;
                    if( null == tokenId){
                        // 登录失败
                        Toast.makeText(LoginFragment.getContext(),"登录失败，请重试", LENGTH_SHORT).show();
                        LoginFragment.getmPassword().setText("");
                    }else{
                        // 登录成功，将用户名密码存入到 SharePreference
                        SharedPreferences.Editor editor =  getSharedPreferences("UserInfo",MODE_PRIVATE).edit();
                        editor.putString("UserTelephone",UserInfoContext.mUser.getTelephone());
                        /*editor.putString("UserPassword",UserInfoContext.mUser.getPassword());*/
                        editor.putBoolean("isLogin",true);
                        editor.putInt("UserId",UserInfoContext.mUser.getId());
                        editor.putString("UserName",UserInfoContext.mUser.getUserName());
                        editor.putString("tokenId",tokenId);
                        editor.putString("UserPwd",UserInfoContext.mUser.getPassword());
                        editor.putString("UserImage",UserInfoContext.mUser.getUserImage());
                        editor.putString("UserEmail",UserInfoContext.mUser.getEmail());

                        // 要记得提交
                        editor.commit();
                        Toast.makeText(LoginActivity.this,"登录成功",LENGTH_SHORT).show();
                        // 跳转到主页面
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName(LoginActivity.this,MainActivity.class));
                        // 传递一个参数，表示是第一次进入 MainActivity 要进行用户信息的补全。
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isFirstToMain",true);
                        intent.putExtras(bundle);
                        LoginActivity.this.startActivity(intent);
                    }
                    break;
                case 2:
                    // 验证码倒计时
                    MyCountDownUtil myCountDownUtil = new MyCountDownUtil(60000,1000,(Button) msg.obj);
                    myCountDownUtil.start();
                    break;
                case 3:
                    Toast.makeText(LoginActivity.this,"获取验证码失败，请重试！",LENGTH_SHORT).show();
                    break;
                case 4:
                    userImageStr.setText((String)msg.obj);
                    break;
                case 5:
                    Toast.makeText(LoginActivity.this,"验证码错误,请重试！",LENGTH_SHORT).show();
                    break;
                case 6:
                    User user = (User) msg.obj;
                    if(user != null){
                        // 登录成功，将用户名密码存入到 SharePreference
                        UserInfoContext.mUser = user;
                        SharedPreferences.Editor editor =  getSharedPreferences("UserInfo",MODE_PRIVATE).edit();
                        editor.putString("UserTelephone",UserInfoContext.mUser.getTelephone());
                        /*editor.putString("UserPassword",UserInfoContext.mUser.getPassword());*/
                        editor.putBoolean("isLogin",true);
                        editor.putInt("UserId",UserInfoContext.mUser.getId());
                        editor.putString("UserName",UserInfoContext.mUser.getUserName());
                        editor.putString("UserPwd",UserInfoContext.mUser.getPassword());
                        editor.putString("tokenId","tokenId");
                        editor.putString("UserImage",UserInfoContext.mUser.getUserImage());
                        editor.putString("UserEmail",UserInfoContext.mUser.getEmail());
                        // 要记得提交
                        editor.commit();
                        Toast.makeText(LoginActivity.this,"登录成功",LENGTH_SHORT).show();
                        // 跳转到主页面
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName(LoginActivity.this,MainActivity.class));
                        // 传递一个参数，表示是第一次进入 MainActivity 要进行用户信息的补全。
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isFirstToMain",true);
                        intent.putExtras(bundle);
                        LoginActivity.this.startActivity(intent);
                    }else{
                        Toast.makeText(LoginActivity.this,"用户名重复,请重试！",LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    private LoginFragment LoginFragment;



     /*重写 onRequestPermissionsResult() 方法   权限申请完毕后会回调该函数 通过该函数可以判断是否获取到所需要的权限。
     * grantResults 为授权结果  永不为空
     *  只有两个值 ： {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
      *     or {@link android.content.pm.PackageManager#PERMISSION_DENIED}
     * */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length >0){
                    // 遍历结果 ，看是否全部授权了
                    for(int result : grantResults){
                        if(result != PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(this,"需要获取到全部权限才可以运行程序",LENGTH_SHORT).show();
                            onDestroy();
                            return ;
                        }
                    }
                }else{
                    // 当 grantResults 的长度 <=0 说明发生了未知的错误
                    Toast.makeText(this,"发生未知错误", LENGTH_SHORT).show();
                    finish();
                    return ;
                }
                break;

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // 打开时 先进行动态权限验证
        SharedPreferences sharePreference = getSharedPreferences("UserInfo",MODE_PRIVATE);

       /* SharedPreferences.Editor edit = sharePreference.edit();
        edit.clear();
        edit.commit();*/
        boolean isLogin = sharePreference.getBoolean("isLogin",false);
        if( isLogin ){
            // 已登录 获取用户的信息
            Map<String, ?> all =sharePreference.getAll();
            UserInfoContext.mUser.setId((Integer) all.get("UserID"));
            UserInfoContext.mUser.setTelephone((String) all.get("UserTelephone"));
            UserInfoContext.mUser.setUserName((String) all.get("UserName"));
            UserInfoContext.mUser.setEmail((String)all.get("UserEmail"));
            UserInfoContext.mUser.setUserImage((String)all.get("UserImage"));
            UserInfoContext.mUser.setPassword((String)all.get("UserPwd"));
            MyPost.tokenId = (String) all.get("tokenId");
            MyGet.tokenId = (String) all.get("tokenId");
            // 跳转到主页面中
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(this, MainActivity.class));
            // 使用一个全局的对象来存储用户信息，就不需要进行传递了
            Bundle bundle = new Bundle();
            bundle.putBoolean("isFirstToMain",false);
            intent.putExtras(bundle);
            startActivity(intent);
        }else{
            // 如果没有登录，就停留在登录页面，让用户进行登录
            // 用Fragment 来进行设计吧
            // 首先进入 登录的Fragment
            LoginFragment = new LoginFragment(myLoginCallBack);
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.myFragment,LoginFragment).commitNow();
            RequestPermissionUtil.requestPermission(this);
        }
    }

    private LoginFragmentCallBack myLoginCallBack = new LoginFragmentCallBack() {
        @Override
        public void onTelephoneChanged(String telephone) {
            UserInfoContext.mUser.setTelephone(telephone);
        }

        @Override
        public void onPasswordChanged(String password) {
            UserInfoContext.mUser.setPassword(password);
        }

        @Override
        public void LoginBtn() { // 登录：发送请求进行验证
            // 不能在主线程中进行网络请求
            // 登录验证
            MyThreadPool.doJob(new Runnable() {
                @Override
                public void run() {
                    String url = "UserLogin";
                    Map<String,String> resultVo = (Map<String, String>) MyPost.doPost(url, UserInfoContext.mUser);
                    String tokenId = null;
                    if(resultVo != null){
                        tokenId = resultVo.get("tokenId");
                        String userId = resultVo.get("UserId");
                        String userName = resultVo.get("userName");
                        String userEmail = resultVo.get("userEmail");
                        String userImage = resultVo.get("userImage");
                        UserInfoContext.mUser.setId(Integer.valueOf(userId));
                        UserInfoContext.mUser.setUserName(userName);
                        UserInfoContext.mUser.setUserImage(userImage);
                        UserInfoContext.mUser.setEmail(userEmail);
                    }
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = tokenId;
                    handler.sendMessage(msg);
                }
            });

        }
        @Override
        public void Register() {// 注册话，转换 Fragment
            // 利用 Fragment管理器跳转到 RegisterFragment
            RegisterFragment registerFragment = new RegisterFragment(registerFragmentCallBack);
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.addToBackStack(null)
                    .replace(R.id.myFragment,registerFragment)
                    .commit();
        }
    };

    RegisterFragmentCallBack registerFragmentCallBack = new RegisterFragmentCallBack() {
        @Override
        public void changeUserImage() {
            ShowPopuWIndow.showPopueWindow(LoginActivity.this,1);
        }

        @Override
        public void getVerifyCode(View btn,String email) {
            MyThreadPool.doJob(new Runnable() {
                @Override
                public void run() {
                    Message msg = new Message();
                    Boolean isGet = (Boolean) MyPost.doPost("getVerifyCode",email);
                    if(isGet){
                        msg.what = 2;
                    }else{
                        msg.what = 3;
                    }
                    msg.obj = btn;
                    handler.sendMessage(msg);
                }
            });
        }

        @Override
        public void register(User user,String code) {
            // 传入一个User
            if(user.getEmail() == null || user.getEmail().equals("")){
                Toast.makeText(LoginActivity.this,"请输入邮箱！",LENGTH_SHORT).show();
                return ;
            }
            if(user.getTelephone() == null || user.getTelephone().equals("")){
                Toast.makeText(LoginActivity.this,"请输入手机号码！",LENGTH_SHORT).show();
                return ;
            }
            if(user.getUserName() == null || user.getUserName().equals("")){
                Toast.makeText(LoginActivity.this,"请输入昵称！",LENGTH_SHORT).show();
                return ;
            }
            if(user.getUserImage() == null || user.getUserImage().equals("")){
                Toast.makeText(LoginActivity.this,"请选择头像！",LENGTH_SHORT).show();
                return ;
            }
            if(code == null || code.equals("")){
                Toast.makeText(LoginActivity.this,"请输入验证码！",LENGTH_SHORT).show();
                return ;
            }
            // 都检查无误，就发送注册请求，注册完毕后，携带参数返回到登录页面中
            MyThreadPool.doJob(new Runnable() {
                @Override
                public void run() {
                    Map<String,Object> param = new HashMap<>();
                    param.put("email",user.getEmail());
                    param.put("code",code);
                    Boolean result = (Boolean) MyPost.doPost("userVerifyCode",param);
                    Message msg = new Message();
                   if(result){
                       // 验证成功
                       User user1 = (User) MyPost.doPost("UserRegister",user);
                       msg.what = 6;
                       if(user1.getId() != null){
                           // 注册成功
                           msg.obj = user1;
                       }
                   }else{
                       // 验证失败
                       msg.what  =5;
                   }
                   handler.sendMessage(msg);
                }
            });


        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        // 在这里获取到 Register的图片组件
        userImage = findViewById(R.id.reg_userImage);
        userImageStr = findViewById(R.id.userImageStr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 如果是 相册返回的话
            if (requestCode == 1 && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                //获取到图片的本地地址
                final String picturePath = cursor.getString(columnIndex);
                // 显示图片
                //upload(picturePath);
                Glide.with(this).load(picturePath).into(userImage);
                // 上传图片获取到src
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        String url = (String) MyPost.uploadImage("getImageUrl",picturePath);
                        Message msg = new Message();
                        msg.obj = url;
                        msg.what = 4;
                        handler.sendMessage(msg);
                    }
                });
                cursor.close();
            }
        }
    }
}